package myclassloader;

import java.io.*;

/**
 * 自定义类加载器
 *
 * @Author: cctv
 * @Date: 2019/5/14 14:19
 */
public class MyClassLoader extends ClassLoader {

    private String path;
    private String classloaderName;

    public MyClassLoader(String path, String classloaderName) {
        this.path = path;
        this.classloaderName = classloaderName;
    }

    /**
     * 用于查找类文件
     * 扩展:可以通过网络获取二进制流并生成类
     * 对敏感的class文件进行加密 在findclass解密
     * 还可以对二进制流做手脚 给类添加信息
     * 扩展学习ASM框架、字节码增强技术
     * @param name
     * @return
     */
    @Override
    public Class findClass(String name) {
        byte[] b = loadClassData(name);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassData(String name) {
        name = path + name + ".class";
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = new FileInputStream(new File(name));
            out = new ByteArrayOutputStream();
            int i = 0;
            while ((i = in.read()) != -1) {
                out.write(i);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return out.toByteArray();

    }
}
